package com.walle.ak47.commons.jaxrs.cxf.interceptor;

import java.util.List;
import java.util.TreeMap;

import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.message.Message;
import org.apache.cxf.message.XMLMessage;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.walle.ak47.commons.jaxrs.constant.ProtocolParam;
import com.walle.ak47.commons.jaxrs.cxf.header.HeaderHolder;
import com.walle.ak47.commons.jaxrs.cxf.header.HeaderInfo;

/**
 * 调用webservice前进行权限判断
 * 
 * @author admin
 * 
 */
public class CheckHeader extends AbstractPhaseInterceptor<XMLMessage> {

	@SuppressWarnings("unused")
	private static final Logger LOG = LoggerFactory
			.getLogger(CheckHeader.class);

	public CheckHeader() {
		super(Phase.PRE_INVOKE);// 该拦截器在调用前拦截HttpHeader信息
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public void handleMessage(XMLMessage msg) throws Fault {
		try {
			TreeMap<String, List> headers = (TreeMap<String, List>) msg
					.get(Message.PROTOCOL_HEADERS);
			List list = (List) headers.get(ProtocolParam.TOKEN_HEADER);
			if (list == null || list.size() == 0) {
				throw new Exception("【X-AUTH-HEADER头校验】不存在!");
			}
			String xAuthHeader = list.get(0).toString();

			HeaderInfo header = HeaderHolder.getHeader();
			if (!header.checkAndGet(xAuthHeader))
				throw new Exception("【X-AUTH-HEADER头校验】格式错误!");

		} catch (Exception e) {
			throw new Fault(new IllegalAccessException(e.getMessage()));
		}

	}
}
